using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SCIENEW {
    public class ComponentIronFurnace : ComponentExFurnace {
        public SubsystemParticles m_subsystemParticles;

        public Dictionary<Point3, FireParticleSystem> m_particleSystemsByCell = [];

        public override float Speed { get; set; } = 0.2f;

        public override void ReplaceFurnace(Point3 coordinates) {
            TerrainChunk chunkAtCell = m_subsystemTerrain.Terrain.GetChunkAtCell(coordinates.X, coordinates.Z);
            if (chunkAtCell != null
                && chunkAtCell.State == TerrainChunkState.Valid) {
                int cellValue = m_subsystemTerrain.Terrain.GetCellValue(coordinates.X, coordinates.Y, coordinates.Z);
                int direction = IronFurnaceDevice.GetDirection_Static(cellValue);
                int deviceValue = DevicesBlockManager.GetDeviceValueByType(typeof(IronFurnaceDevice), m_heatLevel > 0 ? 0b100 | direction : direction);
                m_subsystemTerrain.ChangeCell(coordinates.X, coordinates.Y, coordinates.Z, deviceValue);
                if (m_heatLevel > 0) AddFire(coordinates);
                else RemoveFire(coordinates);
            }
        }

        public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap) {
            base.Load(valuesDictionary, idToEntityMap);
            m_subsystemParticles = Project.FindSubsystem<SubsystemParticles>();
        }

        public override void OnEntityRemoved() {
            base.OnEntityRemoved();
            if (m_particleSystemsByCell.Count > 0) {
                foreach (var fireParticle in m_particleSystemsByCell) {
                    m_subsystemParticles.RemoveParticleSystem(fireParticle.Value);
                }
            }
        }


        public void AddFire(Point3 point) {
            if (m_particleSystemsByCell.ContainsKey(point)) return;

            var v = new Vector3(0.5f, 0.2f, 0.5f);
            float size = 0.15f;
            var fireParticleSystem = new FireParticleSystem(new Vector3(point) + v, size, 16f);
            m_subsystemParticles.AddParticleSystem(fireParticleSystem);
            m_particleSystemsByCell[point] = fireParticleSystem;
        }

        public void RemoveFire(Point3 point) {
            if (!m_particleSystemsByCell.ContainsKey(point)) return;

            FireParticleSystem particleSystem = m_particleSystemsByCell[point];
            m_subsystemParticles.RemoveParticleSystem(particleSystem);
            m_particleSystemsByCell.Remove(point);
        }
    }
}